package gov.gfbzb.advice.interceptor;

import gov.gfbzb.advice.annotation.AuthCheck;
import gov.gfbzb.advice.entity.Enum.UserRoleEnum;
import gov.gfbzb.advice.entity.JwtProperties;
import gov.gfbzb.advice.exception.BusinessException;
import gov.gfbzb.advice.exception.ErrorCode;
import gov.gfbzb.advice.service.IUserService;
import gov.gfbzb.advice.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 权限校验 AOP
 */
@Log4j2
@Aspect
@Component
public class AuthInterceptor {

    @Autowired
    private IUserService userService;

    /**
     * 执行拦截
     *
     * @param joinPoint
     * @param authCheck
     * @return
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustAdmin = authCheck.mustAdmin();
        // 不需要权限，放行
        if (Objects.equals(mustAdmin, "")) {
            return joinPoint.proceed();
        }

        // 必须有该权限才通过
        if (StringUtils.isNotBlank(mustAdmin)) {
            Claims claims = userService.getClaims();
            String phone = claims.get("phone", String.class);
            String role = claims.get("role", String.class);
            if (UserRoleEnum.getEnumByValue(role) == UserRoleEnum.SUPERADMIN||UserRoleEnum.getEnumByValue(role) == UserRoleEnum.AREAADMIN){
                // 通过权限校验，放行
                return joinPoint.proceed();
            }
            log.info("{}，申请接口，进行权限验证，未通过",phone);
        }
        throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
    }
}

